package test.websec;

import javax.annotation.Resource;

import org.fox.beetl.ext.spring.mvc.BeetlViewResolver;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/*")
// 实际上一般不应该在Action里面做用户密码验证这些可能牵涉到数据库和事务操作的功能，这里是简便起见
public class Action {
	/**
	 * 安全验证管理器
	 */
	private AuthenticationManager authenticationManager = null;

	/**
	 * 安全验证管理器
	 *
	 * @param authenticationManager
	 */
	@Resource(name = "testAuthenticationManager")
	@Required
	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	@RequestMapping("login.html")
	public String login() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if ((authentication == null) || (authentication instanceof AnonymousAuthenticationToken)
				|| !authentication.isAuthenticated()) {
			// 如果未认证或匿名登录 打开登录页面
			return "login";
		} else {
			// 如果登录了重定向到首页
			return BeetlViewResolver.redirect("/index.html");
		}
	}

	/**
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping("login.do")
	public String login(@RequestParam("name") String name, @RequestParam("password") String password) {
		try {
			// 验证用户名密码，获取验证凭证
			Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
					name, password));

			if (authentication != null) {
				// 将认证凭证添加到上下文
				SecurityContextHolder.getContext().setAuthentication(authentication);
			}
		} catch (ProviderNotFoundException e) { // 认证失败
		}

		return BeetlViewResolver.redirect("login.html");
	}

	@RequestMapping("index.html")
	public String index() {
		return "index";
	}

	@RequestMapping("admin.html")
	public String admin() {
		return "admin";
	}
}
